import React, { useState, useCallback, useRef, forwardRef, useImperativeHandle } from 'react';
import { message, Space, Upload } from 'antd';
import { InboxOutlined } from '@ant-design/icons';

// 定义组件的ref类型
export interface FileDropZoneRef {
  reset: () => void;
}

interface FileDropZoneProps {
  onFilesDropped: (files: File[], filePaths?: string[]) => void;
  onFilesSelected?: (files: File[]) => void;
  title?: string;
  description?: string;
  disabled?: boolean;
  style?: React.CSSProperties;
}

interface EnhancedFile extends File {
  path?: string;
}

/**
 * 通用文件拖放组件
 * 提供文件拖放和选择功能，并尝试获取文件路径信息
 */
export const FileDropZone = forwardRef<FileDropZoneRef, FileDropZoneProps>((props, ref) => {
  const { onFilesDropped, onFilesSelected, title = '点击或拖拽文件到此处', description = '支持批量选择多个文件', disabled = false, style } = props;
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const changeDebounceRef = useRef<any>(null);
  const lastEmitSignatureRef = useRef<string | null>(null);
  const uploadInstanceRef = useRef<any>(null); // 用于引用Upload组件实例

  /**
   * 从文件对象中提取路径信息
   */
  const extractFilePaths = useCallback((files: File[]): string[] => {
    const paths: string[] = [];
    
    for (const file of files) {
      let filePath: string | undefined = (file as EnhancedFile).path;
      
      // 如果path属性不存在，尝试使用electron提供的方法获取路径
      if (!filePath && (window as any).electron?.getPathForFile) {
        try {
          filePath = (window as any).electron.getPathForFile(file);
        } catch (pathError) {
          console.warn('通过getPathForFile获取路径失败:', pathError);
        }
      }
      
      if (filePath) {
        paths.push(filePath);
      }
    }
    
    return paths;
  }, []);

  /**
   * 处理文件拖放
   */
  const emitFilesIfNew = useCallback((files: File[]) => {
    if (!files || files.length === 0) return;
    // build signature to dedupe repeated events
    const sig = files.map(f => `${(f as any).path || f.name}:${f.size}:${(f as any).lastModified || 0}`).sort().join('|');
    if (lastEmitSignatureRef.current === sig) return; // duplicate batch
    lastEmitSignatureRef.current = sig;

    try {
      const filePaths = extractFilePaths(files);
      onFilesDropped(files, filePaths);
      if (onFilesSelected) onFilesSelected(files);
    } catch (error) {
      console.error('处理拖放文件时出错:', error);
      message.error('处理拖放文件失败，请重试');
    }
  }, [extractFilePaths, onFilesDropped, onFilesSelected]);

  const handleDrop = useCallback((files: File[]) => {
    if (disabled) return;
    if (!files || files.length === 0) {
      message.warning('未检测到有效的本地文件，仅支持本地文件拖放');
      return;
    }
    // 清空前一次的文件签名，确保新的文件列表可以被处理
    lastEmitSignatureRef.current = null;
    emitFilesIfNew(files);
  }, [disabled, emitFilesIfNew]);

  /**
   * 处理文件选择
   */
  const handleFileSelect = useCallback((files: File[]) => {
    if (disabled) return;
    if (!files || files.length === 0) return;
    // 清空前一次的文件签名，确保新的文件列表可以被处理
    lastEmitSignatureRef.current = null;
    emitFilesIfNew(files);
  }, [disabled, emitFilesIfNew]);

  /**
   * 触发文件选择对话框
   */
  const triggerFileSelect = useCallback(() => {
    if (disabled || !fileInputRef.current) return;
    fileInputRef.current.click();
  }, [disabled]);

  const { Dragger } = Upload;

  const uploadProps = {
    multiple: true,
    beforeUpload: (file: File) => {
      // Prevent automatic upload; we only want the File objects
      return false;
    },
    customRequest: ({ file, onSuccess }: any) => {
      // customRequest is not used; handle via onChange
      setTimeout(() => onSuccess && onSuccess('ok'));
    },
    onChange: (info: any) => {
      // Debounce onChange bursts from Upload (Dragger may emit several events when multiple files are added)
      const fileList: File[] = info.fileList.map((f: any) => f.originFileObj).filter(Boolean);
      if (changeDebounceRef.current) clearTimeout(changeDebounceRef.current);
      changeDebounceRef.current = setTimeout(() => {
        handleFileSelect(fileList);
        changeDebounceRef.current = null;
      }, 150);
    },
    showUploadList: false,
    disabled,
    fileList: [] // 确保始终从空文件列表开始
  } as any;

  // 暴露重置方法给父组件
  useImperativeHandle(ref, () => ({
    reset: () => {
      // 清除文件签名
      lastEmitSignatureRef.current = null;
      
      // 清除防抖定时器
      if (changeDebounceRef.current) {
        clearTimeout(changeDebounceRef.current);
        changeDebounceRef.current = null;
      }
      
      // 重置文件输入框，这是解决问题的关键
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
      
      // 重置Upload组件的内部状态
      if (uploadInstanceRef.current) {
        uploadInstanceRef.current.value = '';
      }
    }
  }));

  return (
    <Dragger 
      {...uploadProps} 
      ref={uploadInstanceRef}
      style={{ padding: 12, borderRadius: 8, ...(style || {}) }}
    >
      <Space direction="vertical" size="large" style={{ width: '100%', textAlign: 'center' }}>
        <InboxOutlined style={{ fontSize: 48, color: disabled ? '#d9d9d9' : '#52c41a' }} />
        <div>
          <p style={{ fontSize: 16, marginBottom: 8, fontWeight: 'bold' }}>{title}</p>
          <p style={{ color: '#666', fontSize: 14 }}>{description}</p>
        </div>
      </Space>
    </Dragger>
  );
});

export default FileDropZone;